﻿using System;
using System.Collections.Generic;
using System.Linq;

using RexToy;
using RexToy.Logging;
using RexToy.ORM;

using MGAS.Model.Entity;

namespace MGAS.Model
{
    class DBHistoryManager : IHistoryManager
    {
        private static ILog _log = LogContext.GetLogger<DBHistoryManager>();

        private Exception _lastError;

        private ISensorDataBlock _block;
        public void SetDataSource(ISensorDataBlock block)
        {
            ExceptionBase.Throw_IfArgumentNull(block, "block");
            _block = block;
            _block.SensorDataChanged += new EventHandler<SensorDataChangedEventArgs>(_block_SensorDataChanged);
        }

        void _block_SensorDataChanged(object sender, SensorDataChangedEventArgs e)
        {
            var d = _block.GetData(e.Id);
            History h = new History() { SensorID = d.ID, Status = d.Status, Unit = d.Unit, Value = d.Value, LogTime = DateTime.Now };

            try
            {
                using (var s = SessionFactory.OpenSession())
                {
                    s.Create(h);
                }
            }
            catch (Exception ex)
            {
                //TODO:prevent log flood, skip similar exception in [a specific period]
                if (_lastError == null)
                    _lastError = ex;
                else
                {
                    if (_lastError.GetType() == ex.GetType())
                        return;
                }

                _log.Error(ex.Message);
                _log.Error(ex.ToString());
            }
        }

        public IEnumerable<History> FindHistoryByAddress(int addressId)
        {
            using (var s = SessionFactory.OpenSession())
            {
                return s.FindBy<History>(h => h.SensorID == addressId).OrderByDescending(h => h.LogTime);
            }
        }
    }
}
